/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 StdAsymmetricEncrypter.cpp. Created on: 03.09.2009 11:40:38
 */

#include "smartobjects/encrypters/StdAsymmetricEncrypter.hpp"

namespace smartobjects {

const std::string StdAsymmetricEncrypter::ALGORITHM_NAME = "RSA";
const unsigned long StdAsymmetricEncrypter::KEY_LENGTH = 1024;

StdAsymmetricEncrypter::StdAsymmetricEncrypter()
		: m_pEncrypter(NULL), m_pDecrypter(NULL), m_poPublicKey(NULL), m_poPrivateKey(NULL) {

}

StdAsymmetricEncrypter::~StdAsymmetricEncrypter() {
	if(m_pEncrypter) {
		RSA_free(m_pEncrypter);
		m_pEncrypter = NULL;
	}
	if(m_pDecrypter) {
		RSA_free(m_pDecrypter);
		m_pDecrypter = NULL;
	}

	if(m_poPublicKey) {
		m_poPublicKey->release();
		m_poPublicKey = NULL;
	}

	if(m_poPrivateKey) {
		m_poPrivateKey->release();
		m_poPrivateKey = NULL;
	}
}

void StdAsymmetricEncrypter::initCipher( PrivateKey* poKey ) {
	if(poKey->getKeyData()->getLen() == 0) {
		throw GeneralSecurityException(
			boost::format("Unable to initialize cipher with empty RSA private key!")
		);
	}

	if(m_pDecrypter) {
		RSA_free(m_pDecrypter);
		m_pDecrypter = NULL;
	}

	if(m_poPrivateKey) {
		m_poPrivateKey->release();
		m_poPrivateKey = NULL;
	}

	const unsigned char* pBuf = poKey->getKeyData()->getData();
	m_pDecrypter = d2i_RSAPrivateKey(NULL, &pBuf, poKey->getKeyData()->getLen() );

	if(m_pDecrypter == NULL)
		throw GeneralSecurityException(
			boost::format("Unable to initialize cipher with RSA private key data!")
		);

	m_poPrivateKey = poKey;
	m_poPrivateKey->addRef();
}

void StdAsymmetricEncrypter::initCipher( PublicKey* poKey ) {
	if(poKey->getKeyData()->getLen() == 0) {
		throw GeneralSecurityException(
			boost::format("Unable to initialize cipher with empty RSA private key!")
		);
	}

	if(m_pEncrypter) {
		RSA_free(m_pEncrypter);
		m_pEncrypter = NULL;
	}

	if(m_poPublicKey) {
		m_poPublicKey->release();
		m_poPublicKey = NULL;
	}

	const unsigned char* pBuf = poKey->getKeyData()->getData();
	m_pEncrypter = d2i_RSA_PUBKEY(NULL, &pBuf, poKey->getKeyData()->getLen() );

	if(m_pEncrypter == NULL)
		throw GeneralSecurityException(
			boost::format("Unable to initialize cipher with RSA private key data!")
		);

	m_poPublicKey = poKey;
	m_poPublicKey->addRef();
}

PublicKey* StdAsymmetricEncrypter::getPublicKey() {
	return m_poPublicKey;
}

PrivateKey* StdAsymmetricEncrypter::getPrivateKey() {
	return m_poPrivateKey;
}

PublicKey* StdAsymmetricEncrypter::decodePublicKey(ByteBuffer*  poBuffer) {
	PublicKey* poResult = new PublicKey();
	unsigned int nKeyLen = poBuffer->getLenFromPos();
	poResult->getKeyData()->append(poBuffer->getDataAtPos(), nKeyLen);
	poBuffer->seek( nKeyLen );
	return poResult;
}

void StdAsymmetricEncrypter::encodePublicKey(PublicKey* poKey, ByteBuffer*  poBuffer ) {
	poBuffer->append ( poKey->getKeyData() );
}

KeyPair* StdAsymmetricEncrypter::generateKeyPair() {
	RSA* pRSAKeyPair;
	pRSAKeyPair = RSA_generate_key(KEY_LENGTH, RSA_F4, NULL, NULL);
	if(pRSAKeyPair == NULL)
		throw GeneralSecurityException(
			boost::format("Unable to generate RSA key pairs!")
		);

	PublicKey* poPublicKey = new PublicKey() ;
	PrivateKey* poPrivateKey = new PrivateKey();

	int nPublicKeyLen = i2d_RSA_PUBKEY(pRSAKeyPair, NULL);
	poPublicKey->getKeyData()->setLen(nPublicKeyLen);
	unsigned char* pBuf = poPublicKey->getKeyData()->getData();
	i2d_RSA_PUBKEY ( pRSAKeyPair, &pBuf );

	int nPrivateKeyLen = i2d_RSAPrivateKey(pRSAKeyPair, NULL);
	poPrivateKey->getKeyData()->setLen(nPrivateKeyLen);
	pBuf = poPrivateKey->getKeyData()->getData();
	i2d_RSAPrivateKey ( pRSAKeyPair, &pBuf );

	KeyPair* poResult = new KeyPair(poPublicKey, poPrivateKey);
	poPublicKey->release();
	poPrivateKey->release();
	RSA_free(pRSAKeyPair);
	return poResult;
}

void StdAsymmetricEncrypter::encrypt ( ByteBuffer* poInputData, ByteBuffer* poOutput )  {
	boost::recursive_mutex::scoped_lock oLock(m_mxEncrypter);
	if(m_pEncrypter==NULL)
		throw GeneralSecurityException(
			boost::format("Encrypter must be initialized with a public key before run RSA encryption!")
		);

	int nNeedSize = RSA_size(m_pEncrypter);
	int nWritePos = poOutput->getLen();
	poOutput->setLen(nWritePos+nNeedSize);

	int nResultCode = RSA_public_encrypt(
			poInputData->getLenFromPos(),
			poInputData->getDataAtPos(),
			poOutput->getData() + nWritePos,
			m_pEncrypter,
			RSA_PKCS1_PADDING
	);

	if(nResultCode < 0 )
		throw GeneralSecurityException(
			boost::format("Unable to encrypt data with RSA! Result code: %1%") %nResultCode
		);

	poInputData->seek(poInputData->getLenFromPos());
}

void StdAsymmetricEncrypter::decrypt(ByteBuffer* poEncryptedData, ByteBuffer* poOutput) {
	boost::recursive_mutex::scoped_lock oLock(m_mxDecrypter);

	if(m_pDecrypter==NULL)
		throw GeneralSecurityException(
			boost::format("Decrypter must be initialized with a private key before run RSA decryption!")
		);

	int nNeedSize = RSA_size(m_pDecrypter);
	int nWritePos = poOutput->getLen();
	poOutput->setLen(nWritePos+nNeedSize);

	int nResultCode = RSA_private_decrypt(
			poEncryptedData->getLenFromPos(),
			poEncryptedData->getDataAtPos(),
			poOutput->getData() + nWritePos,
			m_pDecrypter,
			RSA_PKCS1_PADDING
	);

	if(nResultCode < 0 )
		throw GeneralSecurityException(
			boost::format("Unable to encrypt data with RSA! Result code: %1%") %nResultCode
		);

	poOutput->setLen( nResultCode );
	poEncryptedData->seek(poEncryptedData->getLenFromPos());
}

const std::string& StdAsymmetricEncrypter::getAlgorithm() const {
	return ALGORITHM_NAME;
}

}
